package com.ErpCoreWeb.View;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.UI.CTButtonInView;
import com.ErpCoreModel.UI.CView;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class SetTButton
 */
@WebServlet("/SetTButton")
public class SetTButton extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CUser m_User = null;
    public CTable m_Table = null;
    public CView m_View = null;
    boolean m_bIsNew = false;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SetTButton() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
		try {
			m_User = (CUser) request.getSession().getAttribute("User");

			String vid = request.getParameter("id");
			if (Global.IsNullParameter(vid)) {
				response.getWriter().close();
			}
			m_View = (CView) Global.GetCtx(this.getServletContext())
					.getViewMgr().Find(Util.GetUUID(vid));
			if (m_View == null) {
				response.getWriter().close();
			}
			m_Table = (CTable) Global.GetCtx(this.getServletContext())
					.getTableMgr().Find(m_View.getFW_Table_id());


		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
        	GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
        	Cancel();
            return ;
        }
        else if (Action.equalsIgnoreCase("Delete"))
        {
        	Delete();
            return ;
        }
        else if (Action.equalsIgnoreCase("Add"))
        {
        	Add();
            return ;
        }
	}

    void GetData()
    {
        List<CTButtonInView> lstObj = m_View.getTButtonInViewMgr().GetListOrderByIdx();

        String sData = "";

        int iCount = 0;
        for (CTButtonInView tiv : lstObj)
        {
            sData += String.format("{ \"id\": \"%s\",\"Caption\":\"%s\",\"Url\":\"%s\"},"
                , tiv.getId().toString(), tiv.getCaption(), tiv.getUrl());

            iCount++;
        }
		if (sData.endsWith(","))
			sData = sData.substring(0, sData.length() - 1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, iCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void PostData()
    {

        String GridData = request.getParameter("GridData");
        if (Global.IsNullParameter(GridData))
        {
            //已经被删除完，保存退出
            m_View.getTButtonInViewMgr().Save();
            return;
        }

        String[] arr1 = GridData.split(";");
        for (int i = 0; i < arr1.length; i++)
        {
            String[] arr2 = arr1[i].split("\\|");

            CTButtonInView tiv = (CTButtonInView)m_View.getTButtonInViewMgr().Find(Util.GetUUID(arr2[0]));
            tiv.setIdx ( i);
            tiv.setCaption ( arr2[1]);
            tiv.setUrl ( arr2[2]);
            m_View.getTButtonInViewMgr().Update(tiv);
        }
        m_View.getTButtonInViewMgr().Save();
    }
    void Cancel()
    {
        m_View.getTButtonInViewMgr().Cancel();
    }
    void Delete()
    {
        String delid = request.getParameter("delid");
        if (Global.IsNullParameter(delid))
        {
            try {
				response.getWriter().print("请选择一项！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }

        m_View.getTButtonInViewMgr().Delete(Util.GetUUID(delid));

    }

    void Add()
    {
		try {
			String txtCaption = request.getParameter("txtCaption");
			String txtUrl = request.getParameter("txtUrl");
			if (Global.IsNullParameter(txtCaption)) {
				response.getWriter().print("请输入标题！");
				return;
			}
			if (Global.IsNullParameter(txtUrl)) {
				response.getWriter().print("请输入Url！");
				return;
			}

			CTButtonInView tiv = new CTButtonInView();
			tiv.Ctx = Global.GetCtx(this.getServletContext());
			tiv.setUI_View_id(m_View.getId());
			tiv.setCaption(txtCaption.trim());
			tiv.setUrl(txtUrl.trim());
			tiv.setIdx(m_View.getTButtonInViewMgr().NewIdx());
			tiv.setCreator(m_User.getId());
			m_View.getTButtonInViewMgr().AddNew(tiv);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
